package com.module.user.ui.info

import android.content.Intent
import android.net.Uri
import android.util.Log
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.common.app.base.AppPictureSelectionActivity
import com.common.app.data.bean.BaseCityModel
import com.common.app.data.bean.DialogButBean
import com.common.app.data.bean.KeyEvents
import com.common.app.data.bean.KeyPre
import com.common.app.dialog.CommonDialog
import com.common.app.dialog.CommonDoubleItemDialog
import com.common.app.helper.*
import com.common.app.utls.Constants
import com.common.app.utls.Constants.LOCAL_FILE_SCHEME
import com.common.app.utls.HeadTitleUtils
import com.common.base.app.extras.*
import com.common.base.utils.*
import com.common.base.widget.popup.RecyclerPopupWindow
import com.jeremyliao.liveeventbus.LiveEventBus
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.utils.MediaUtils
import com.module.user.R
import com.module.user.databinding.UserActivityPersonInfoBinding
import com.module.user.ui.completePersonalInfo.DateBirthSelectDialog
import com.module.user.ui.completePersonalInfo.GenderSelectDialog
import com.module.user.ui.completePersonalInfo.HeightSelectDialog
import com.module.user.ui.completePersonalInfo.WeightSelectDialog
import com.module.user.ui.modifyNikeName.ModifyNikeNameActivity
import com.module.user.utils.UserPermissionUtils
import java.io.File
import java.util.ArrayList

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2022/8/29
 * <p>
 * 描述：个人资料页面
 * <p>
 * 修订历史：
 */
class PersonInfoActivity : AppPictureSelectionActivity<UserActivityPersonInfoBinding, PersonInfoViewModel>(),
    View.OnClickListener, CommonDoubleItemDialog.OnCommonDoubleItemClickListener{

    override fun getViewModel(): Class<PersonInfoViewModel> = PersonInfoViewModel::class.java

    override fun getViewContentBinding() = UserActivityPersonInfoBinding.inflate(layoutInflater)

    override fun isShowToolBar(): Boolean = false
    override fun isStatusBarTranslate(): Boolean = true

    private var imgId: Long = 0
    private var imgUrl: String? = null

    private var launcherResult: ActivityResultLauncher<Intent?>? = null
    private var modifyLauncherResult: ActivityResultLauncher<Intent>? = null

    /**
     *
     */
    private var commonDoubleItemDialog: CommonDoubleItemDialog? = null

    private val dateBirthSelectDialog : DateBirthSelectDialog? by lazy{ DateBirthSelectDialog(this) }
    private val genderSelectDialog : GenderSelectDialog? by lazy{ GenderSelectDialog(this) }
    private val heightSelectDialog : HeightSelectDialog? by lazy{ HeightSelectDialog(this) }
    private val weightSelectDialog : WeightSelectDialog? by lazy{ WeightSelectDialog(this) }

    override fun initViews() {
        super.initViews()
        StatusBarUtils.setStatusBarHeight(mViewContentBinding.statusView)
        StatusBarUtils.setStatusBarForegroundColor(this, true)
        val headTitleUtils = HeadTitleUtils(this)
        headTitleUtils.setTitle(resources.getString(R.string.user_per_info_hint))
        headTitleUtils.setLineStyle(10)


        // 注册需要写在onCreate或Fragment onAttach里，否则会报java.lang.IllegalStateException异常
        launcherResult = createActivityResultLauncher()
        initPictureStyle()

        modifyLauncherResult = createModifyResultLauncher()

        commonDoubleItemDialog = CommonDoubleItemDialog(this)
        commonDoubleItemDialog?.setTopBtnText("从手机相册选取")

        mViewContentBinding.kvGender.tag = "1"
    }

    override fun onResume() {
        super.onResume()
    }

    override fun initEvents() {
        super.initEvents()
        mViewContentBinding.headBg.setOnClickListener(this)
        mViewContentBinding.kvNikeName.setOnClickListener(this)
        mViewContentBinding.kvDateBirth.setOnClickListener(this)
        mViewContentBinding.kvGender.setOnClickListener(this)
        mViewContentBinding.kvHeight.setOnClickListener(this)
        mViewContentBinding.kvBodyWeight.setOnClickListener(this)
        mViewContentBinding.tvExtLogin.setOnClickListener(this)

        dateBirthSelectDialog?.setListener(object : DateBirthSelectDialog.OnSelectListener{
            override fun onSelectClick(
                yearBean: BaseCityModel?,
                monthBean: BaseCityModel?,
                dayBean: BaseCityModel?
            ) {
                mViewContentBinding.kvDateBirth.setValue("${yearBean?.code}-${monthBean?.code}-${dayBean?.code}")
                modifyUsrInfo()
            }
        })
        genderSelectDialog?.setListener(object : GenderSelectDialog.OnSelectListener{
            override fun onSelectClick(mBean: BaseCityModel) {
                mViewContentBinding.kvGender.setValue(mBean.name)
                mViewContentBinding.kvGender.tag = mBean.code.toInt()
                modifyUsrInfo()
            }
        })
        heightSelectDialog?.setListener(object : HeightSelectDialog.OnSelectListener{
            override fun onSelectClick(mBean: BaseCityModel) {
                setHeightUi(mBean.name.toInt())
                modifyUsrInfo()
            }
        })
        weightSelectDialog?.setListener(object : WeightSelectDialog.OnSelectListener{
            override fun onSelectClick(mBean: BaseCityModel) {
                setBodyWeightUi(mBean.name.toInt())
                modifyUsrInfo()
            }
        })

        LiveEventBus.get(KeyEvents.KEY_CLOSE_ACTIVITY).observe(this) {
            if (it != null && it == PersonInfoActivity::class.java) {
                finish()
            }
        }


        commonDoubleItemDialog?.setOnCommonDoubleItemClickListener(this)
    }

    override fun lazyInitData() {
        super.lazyInitData()
        mViewModel.getCache(this)
        mViewContentBinding.imgHead.loadId(R.drawable.common_user_def_head_icon, 100f)
        Constants.userBean?.let {
            imgUrl = it.avatar_url
            mViewContentBinding.imgHead.loadCircle(it.avatar_url)
            mViewContentBinding.kvNikeName.setValue(if (it.getUserNickname().isNullOrEmpty()) it.mobile else it.getUserNickname())

            mViewContentBinding.kvGender.setValue(when(it.sex){
                0-> getString(R.string.common_sex_female_mm_hint)
                else-> getString(R.string.common_sex_male_mm_hint)
            })
            mViewContentBinding.kvGender.tag = it.sex.toString()

            it.birthday?.let {birthdayIt->
                mViewContentBinding.kvDateBirth.setValue(birthdayIt)
            }

            (it.height>0).yes {
                setHeightUi(it.height)
            }
            (it.weight>0).yes {
                setBodyWeightUi(it.weight)
            }
        }
    }

    override fun onClick(v: View?) {
        when (v) {
            //修改头像
            mViewContentBinding.headBg -> {
                if (UserPermissionUtils.checkPermission(this)) {
                    if (commonDoubleItemDialog?.isShowing == false) commonDoubleItemDialog?.show()
                }
            }
            mViewContentBinding.kvNikeName -> startActivityResultLauncher<ModifyNikeNameActivity>(modifyLauncherResult, false)
            mViewContentBinding.kvDateBirth -> dateBirthSelectDialog?.show()
            mViewContentBinding.kvGender -> genderSelectDialog?.show()
            mViewContentBinding.kvHeight -> heightSelectDialog?.show()
            mViewContentBinding.kvBodyWeight -> weightSelectDialog?.show()
            //退出登录
            mViewContentBinding.tvExtLogin -> showExitDialog()
        }
    }

    /**
     * 创建一个ActivityResultLauncher
     *
     * @return
     */
    private fun createActivityResultLauncher(): ActivityResultLauncher<Intent?> {
        return registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) { result ->
            val resultCode = result.resultCode
            if (resultCode == RESULT_OK) {
                val selectList = PictureSelector.obtainSelectorList(result.data)
                analyticalSelectResults(selectList)
            } else if (resultCode == RESULT_CANCELED) {
                Log.i(TAG, "onActivityResult PictureSelector Cancel")
            }
        }
    }

    /**
     * 创建一个ActivityResultLauncher
     *
     * @return
     */
    private fun createModifyResultLauncher(): ActivityResultLauncher<Intent> {
        return registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) { result ->
            val resultCode = result.resultCode
            if (resultCode == RESULT_OK) {
                result.data?.let {
                    val mName: String? = it.getStringExtra("nikeName")
                    mName.isNullOrEmpty().no {
                        mViewContentBinding.kvNikeName.setValue(mName)
                        modifyUsrInfo()
                    }
                }
            } else if (resultCode == RESULT_CANCELED) {
                Log.i(TAG, "onActivityResult PictureSelector Cancel")
            }
        }
    }

    /**
     * 处理选择结果
     *
     * @param result
     */
    private fun analyticalSelectResults(result: ArrayList<LocalMedia>) {
        for (media in result) {
            if (media.width == 0 || media.height == 0) {
                if (PictureMimeType.isHasImage(media.mimeType)) {
                    val imageExtraInfo = MediaUtils.getImageSize(this, media.path)
                    media.width = imageExtraInfo.width
                    media.height = imageExtraInfo.height
                } else if (PictureMimeType.isHasVideo(media.mimeType)) {
                    val videoExtraInfo = MediaUtils.getVideoSize(this, media.path)
                    media.width = videoExtraInfo.width
                    media.height = videoExtraInfo.height
                }
            }
            Log.i(TAG, "文件名: " + media.fileName)
            Log.i(TAG, "是否压缩:" + media.isCompressed)
            Log.i(TAG, "压缩:" + media.compressPath)
            Log.i(TAG, "初始路径:" + media.path)
            Log.i(TAG, "绝对路径:" + media.realPath)
            Log.i(TAG, "是否裁剪:" + media.isCut)
            Log.i(TAG, "裁剪:" + media.cutPath)
            Log.i(TAG, "是否开启原图:" + media.isOriginal)
            Log.i(TAG, "原图路径:" + media.originalPath)
            Log.i(TAG, "沙盒路径:" + media.sandboxPath)
            Log.i(TAG, "水印路径:" + media.watermarkPath)
            Log.i(TAG, "视频缩略图:" + media.videoThumbnailPath)
            Log.i(TAG, "原始宽高: " + media.width + "x" + media.height)
            Log.i(TAG, "裁剪宽高: " + media.cropImageWidth + "x" + media.cropImageHeight)
            Log.i(TAG, "文件大小: " + media.size)
        }
        //上传obs
//        Constants.userBean?.let {
//            it.imageUrl = Uri.parse(LOCAL_FILE_SCHEME + result[0].sandboxPath).toString()
//        }

//        mViewContentBinding.imgHead.loadRound(Uri.parse(LOCAL_FILE_SCHEME + result[0].sandboxPath).toString(),100)//测试代码
        uploadImage(result[0].sandboxPath)
    }

    //退出登录弹框
    private fun showExitDialog() {
        CommonDialog.newInstance().setTitle("注意").setContent("是否要退出当前账号？")
            .setOnCommonDialogListener(object :
                CommonDialog.OnCommonDialogListener {
                override fun onClick(dialog: CommonDialog, position: Int, data: DialogButBean) {
                    if (position > 0) {
                        UserHelper.logout()
                        LaunchHelper.launchSplash()
                        ActivityCollector.finishAllNotLogin()
                    }
                }
            }).show(supportFragmentManager)
    }


    private fun getUserInfo() {
        mViewModel.getUserInfo().observe(this) {
            it.isSuccess().yes {
                UserHelper.updateUser(UserHelper.getUser(), it.Data)
                lazyInitData()
            }
        }
    }

    private fun modifyUsrInfo() {
        val mNikeName = mViewContentBinding.kvNikeName.getValue().trim()
        val mDateBirth = mViewContentBinding.kvDateBirth.getValue().trim()
        val mHeight = mViewContentBinding.kvHeight.tag.toString().trim().replace(getString(R.string.common_feet_splice),"").replace(getString(R.string.common_feet_splice),"")
        val mBodyWeight = mViewContentBinding.kvBodyWeight.tag.toString().trim().replace(getString(R.string.common_kilogram_splice),"").replace(getString(R.string.common_pound_splice),"")

        showDialogLoading()
        mViewModel.modifyUsrInfo(imageId = imgId, nickname = mNikeName, birthday = mDateBirth, sex = mViewContentBinding.kvGender.tag.toString().toInt(), height = mHeight.toInt(), weight = mBodyWeight.toInt()).observe(this) {
            dismissLoadingDialog()
            it.isSuccess().yes {
                LiveEventBus.get(KeyEvents.KEY_REQUEST_USER_INFO_DATA).post(this)
                getUserInfo()
            }.otherwise {
                showToast(it.Message)
            }
        }
    }

    //开始上传图片
    private fun uploadImage(imgTemp: String) {
        imgId = 0
        val imgFile = File(imgTemp)
        if (imgFile.exists()) {
            showDialogLoading()
            mViewModel.uploadImage(imgFile,"image").observe(this) {

                dismissLoadingDialog()
                LogUtils.e("===>${it}")
                it.isSuccess().yes {
                    it.Data?.url?.let { urlIt->
                        imgId = it.Data?.id?:0
                        imgUrl = urlIt
//                        UserHelper.getUser()?.avatar_url = imgUrl ?: ""
                        mViewContentBinding.imgHead.loadCircle(imgUrl)
                        modifyUsrInfo()
                    }
                }
            }
        }
    }

    fun setHeightUi(mHeight:Int){
        var convertValue = "${mHeight}${getString(R.string.common_centimetre_splice)}"
        (SpUtilsManagement.getInt(KeyPre.KEY_METERING_UNIT_LENGTH,0) !=0).yes {
            convertValue = "${UnitConversionUtils.convertLength(mHeight.toDouble(), UnitConversionUtils.LengthUnit.CM, UnitConversionUtils.LengthUnit.FT).formatDecimal(2)}${getString(R.string.common_feet_splice)}"
        }

        mViewContentBinding.kvHeight.setValue(convertValue)
        mViewContentBinding.kvHeight.tag = mHeight
    }
    fun setBodyWeightUi(mBodyWeight:Int){
        var convertValue = "${mBodyWeight}${getString(R.string.common_kilogram_splice)}"
        (SpUtilsManagement.getInt(KeyPre.KEY_METERING_UNIT_WEIGHT,0) !=0).yes {
            convertValue = "${UnitConversionUtils.convertWeight(mBodyWeight.toDouble(), UnitConversionUtils.WeightUnit.KG, UnitConversionUtils.WeightUnit.LB).formatDecimal(2)}${getString(R.string.common_pound_splice)}"
        }

        mViewContentBinding.kvBodyWeight.setValue(convertValue)
        mViewContentBinding.kvBodyWeight.tag = mBodyWeight
    }

    override fun onTopBtnClick(topValue: String?) {
        selectFromAlbum(true, launcherResult, 1)
    }

    override fun onBottomBtnClick(botValue: String?) {
    }
}